<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="imgurl" :src="imgurl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-if="showprogress" :percentage="percent" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDf8LGuGLAk23nFQKFyShhRv97rMbbKn0x', // 身份识别ID
  SecretKey: 'jEUUFkywf8MK2VifMp43mGUSAdssd8ON' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    imgurl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      percent: 0,
      showprogress: false
    }
  },
  methods: {
    upload (res) {
      this.showprogress = true
      cos.putObject({
        Bucket: 'wangjing-1308304319', /* 必须 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: res.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: res.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
          console.log(this.percent)
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          const imgurl = 'http://' + data.Location
          this.showprogress = false
          this.percent = 0
          this.$emit('upload-img', imgurl)
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
